﻿using B.S.Data.MES.API.Applications.OrcanApplication.Command;
using B.S.Data.MES.API.Dto.TreeDTo;
using B.S.Domain.Accounts;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Data.MES.API.Applications.OrcanApplication.CommandHandler
{
    public class TreeQueryCommandHandler : IRequestHandler<TreeQueryCommand, APIRequst<List<TreeDTOs>>>
    {
        public TreeQueryCommandHandler(IBaseRepository<OrcanClass> orcanRepository)
        {
            OrcanRepository = orcanRepository;
        }

        public IBaseRepository<OrcanClass> OrcanRepository { get; }

        public async Task<APIRequst<List<TreeDTOs>>> Handle(TreeQueryCommand request, CancellationToken cancellationToken)
        {
           var str= await TreeGet(0);
            return new APIRequst<List<TreeDTOs>>
            {
                Code = RequstCode.成功,
                Msg = "获取成功",
                Data = str,
            };
        }
        /// <summary>
        /// 获取树形结构
        /// </summary>
        /// <param name="OrcanId"></param>
        /// <returns></returns>
        public async Task<List<TreeDTOs>> TreeGet(int OrcanId)
        {
            var path = await OrcanRepository.GetAll().Where(a => a.OrganProId == OrcanId).ToListAsync();
            List<TreeDTOs> treeList = new List<TreeDTOs>();
            foreach (var item in path)
            {
                TreeDTOs tree = new TreeDTOs
                {
                    value = item.OranId,
                    label = item.OranCord,
                    children = await TreeGet(item.OranId)
                };
                treeList.Add(tree);
            }
            return treeList;
        }


    }
}
